package jw.webapi.agent;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import jw.config.WxMaConfiguration;
import jw.model.agent.WxAgent;
import jw.model.agent.WxAgentAddress;
import jw.model.agent.WxAgentBalance;
import jw.model.agent.WxAgentBalanceInfo;
import jw.model.login.UserInfo;
import jw.model.login.WxLoginInfo;
import jw.repository.agent.WxAgentAddressRepository;
import jw.repository.agent.WxAgentBalanceInfoRepository;
import jw.repository.agent.WxAgentBalanceRepository;
import jw.repository.agent.WxAgentRepository;
import jw.service.UserTokenManager;
import jw.util.DateUtils;
import jw.util.IpUtil;
import jw.util.OrderNumberUtil;
import jw.util.ResponseUtil;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;


/**
 * 用户接口
 * Created by 天赐美颜郭德纲 on 2020/01/07.
 */
@Controller
@CrossOrigin
@RequestMapping("wx/agent/")
public class AgentWebApi {

    @Autowired
    private WxAgentRepository wxAgentRepository;

    @Autowired
    private WxAgentBalanceRepository wxAgentBalanceRepository;

    @Autowired
    private WxAgentBalanceInfoRepository wxAgentBalanceInfoRepository;

    @Autowired
    private WxAgentAddressRepository wxAgentAddressRepository;



    /**
     * 微信登录
     *
     * @param wxLoginInfo 请求内容，{ code: xxx, userInfo: xxx }
     * @param request     请求对象
     * @return 登录结果
     */
    @RequestMapping("login")
    @ResponseBody
    public Object login(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return ResponseUtil.badArgument();
        }
        String sessionKey = null;
        String openId = null;
        try {
            // 获取小程序服务实例
            WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            // 获取小程序二维码生成实例
//            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            WxMaJscode2SessionResult wxResult = wxMaService.getUserService().getSessionInfo(code);
            sessionKey = wxResult.getSessionKey();
            openId = wxResult.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            return ResponseUtil.fail();
        }

        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null) {
            agent = new WxAgent();
            agent.setOpenId(openId);
            agent.setHeadPicture(userInfo.getAvatarUrl());
            agent.setAgentAdress(userInfo.getCity());
            agent.setName(userInfo.getNickName());
            agent.setStatus(1);
            agent.setLastLoginTime(LocalDateTime.now());
            agent.setLastLoginIp(IpUtil.getIpAddr(request));
            agent.setSessionKey(sessionKey);
            wxAgentRepository.save(agent);
            agent.setCode("WX" + OrderNumberUtil.createAgentNumber(agent.getId()));
            wxAgentRepository.saveAndFlush(agent);
        } else {
            agent.setLastLoginTime(LocalDateTime.now());
            agent.setLastLoginIp(IpUtil.getIpAddr(request));
            agent.setSessionKey(sessionKey);
            wxAgentRepository.saveAndFlush(agent);
        }
        //token
        String token = UserTokenManager.generateToken(agent.getId());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("openId", agent.getOpenId());
        result.put("token", token);
        result.put("userInfo", userInfo);
        return ResponseUtil.ok(result);

    }


    /****
     * 查找下级会员接口
     * @return
     */
    @RequestMapping(value = "findSubAgent",method = RequestMethod.GET)
    @ResponseBody
    public Object findSubAgent(String openId){
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        List<WxAgent>subAgentList = wxAgentRepository.findByParentCode(agent.getCode());
        List<Map<String,Object>> list = new ArrayList<>();
        if (subAgentList.size() > 0){
            for (WxAgent subAgent : subAgentList){
                Map<String,Object> subAgentMap = new HashedMap();
                subAgentMap.put("picture",subAgent.getHeadPicture());
                subAgentMap.put("name",subAgent.getName());
                subAgentMap.put("subAgentCode",subAgent.getCode());
                subAgentMap.put("subAgentId",subAgent.getId());
                list.add(subAgentMap);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("agentList", list);
        return ResponseUtil.ok(result);
    }


    /****
     * 查找用户余额接口
     * @return
     */
    @RequestMapping(value = "findAgentBalance",method = RequestMethod.GET)
    @ResponseBody
    public Object findAgentBalance(String openId){
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        Integer balanceMoney = 0;
        WxAgentBalance balance = wxAgentBalanceRepository.findByAgentCode(agent.getCode());
        if (balance != null){
            balanceMoney = balance.getBalance();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("balanceMoney", balanceMoney);
        return ResponseUtil.ok(result);
    }


    /****
     * 查找用户余额详情接口
     * @return
     */
    @RequestMapping(value = "findAgentBalanceInfo",method = RequestMethod.GET)
    @ResponseBody
    public Object findAgentBalanceInfo(String openId,Integer type,Integer year,Integer month){
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        if (type == null || year == null || month == null){
            return ResponseUtil.fail(1,"参数错误");
        }
        Integer money = 0;
        List<WxAgentBalanceInfo>balanceInfoList = wxAgentBalanceInfoRepository.findInfoList(agent.getId(),1,type,year,month);
        List<Map<String,Object>> list = new ArrayList<>();
        if (balanceInfoList.size() > 0){
            for (WxAgentBalanceInfo info : balanceInfoList){
                Map<String,Object> balanceInfoMap = new HashedMap();
                balanceInfoMap.put("money",info.getMoney());
                balanceInfoMap.put("year",info.getYear());
                balanceInfoMap.put("month",info.getMonth());
                balanceInfoMap.put("detail",info.getDetail());
                balanceInfoMap.put("type",info.getType());//1收入 2支出
                balanceInfoMap.put("time",DateUtils.formatDate(info.getCreateTime()));
                list.add(balanceInfoMap);
                money = money + info.getMoney();
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("balanceInfoList", list);
        result.put("money", money);
        return ResponseUtil.ok(result);
    }


    /***
     * 新增修改代理商地址
     * 如果原来存在默认地址 则新增的地址为默认地址
     * 如果原来不存在默认地址或无地址 则新增的地址为默认地址
     * @param data
     * @return
     */
    @Transactional
    @RequestMapping("addAgentAddress")
    @ResponseBody
    public Object addAgentAddress(@RequestBody String data){
        JSONObject jo = new JSONObject(data);
        String address = jo.getString("address");
        String city = jo.getString("city");
        String country = jo.getString("country");
        String province = jo.getString("province");
        String openId = jo.getString("openId");
        String street = jo.getString("street");
        String receiveName = jo.getString("receiveName");
        String phone = jo.getString("phone");
        Integer isDefault = jo.getInt("isDefault");
        Integer addressId = jo.getInt("addressId");
        if (address == null || city == null || country == null || province == null || openId == null || street == null
                || receiveName == null || phone == null){
            return ResponseUtil.fail(1,"参数错误");
        }
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        WxAgentAddress agentAddress = wxAgentAddressRepository.findOne(addressId);
        if (agentAddress == null){
            agentAddress = new WxAgentAddress();
        }
        if(isDefault == 1){
            WxAgentAddress nowAddress = wxAgentAddressRepository.findByAgentIdAndIsDefault(agent.getId(),1);
            if(nowAddress!=null){
                nowAddress.setIsDefault(0);
                wxAgentAddressRepository.saveAndFlush(nowAddress);
            }
        }
        agentAddress.setIsDefault(isDefault);
        agentAddress.setCity(city);
        agentAddress.setAddress(address);
        agentAddress.setProvince(province);
        agentAddress.setAgentId(agent.getId());
        agentAddress.setCountry("中国");
        agentAddress.setReceiveName(receiveName);
        agentAddress.setPhone(phone);
        agentAddress.setStreet(street);
        wxAgentAddressRepository.save(agentAddress);
        return ResponseUtil.ok();
    }

    /***
     * 获取代理商地址列表
     * isUsed 0 未启用 1 启用地址
     * 启用地址会从登陆接口中返回
     * @return
     */

    @RequestMapping("getAddressList")
    @ResponseBody
    public Object getAddressList(String openId){
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.unlogin();
        }
        List<WxAgentAddress> list = wxAgentAddressRepository.findByAgentId(agent.getId());
        return ResponseUtil.ok(list);
    }

    /***
     * 删除代理商地址
     * @return
     */
    @Transactional
    @RequestMapping("deleteAddress")
    @ResponseBody
    public Object deleteAddress(@RequestBody String data){
        JSONObject jsonObject = new JSONObject(data);
        Integer addressId = jsonObject.getInt("addressId");
        WxAgentAddress address = wxAgentAddressRepository.findOne(addressId);
        if (address == null){
            return ResponseUtil.fail(1,"地址不存在");
        }
        wxAgentAddressRepository.delete(address);
        return ResponseUtil.ok();
    }

    /**
     * 获取地址详情
     * @param id
     * @return
     */
    @RequestMapping("addressDetail")
    @ResponseBody
    public Object getAddressById(Integer id){
       WxAgentAddress wxAgentAddress=wxAgentAddressRepository.findOne(id);
        if (wxAgentAddress == null){
            return ResponseUtil.fail(1,"地址不存在");
        }
        return ResponseUtil.ok(wxAgentAddress);
    }

}
